import PySimpleGUI as sg
import threading
import time

# 主题设置
sg.theme("DarkBlue3")

# ===== 全局状态变量 =====
task1_running = False  # 标记任务是否正在运行
task1_thread = None  # 任务线程对象

# ===== 布局定义 =====
layout = [
    [sg.Text("异步任务控制演示", font=("Arial", 16))],
    [
        sg.Button("开始任务1", key="-START-", size=(10, 2)),
        sg.Button("停止任务1", key="-STOP-", size=(10, 2), disabled=True)
    ],
    [sg.Multiline(
        key="-LOG-",
        disabled=True,
        autoscroll=True,
        size=(60, 15),
        expand_x=True,
        expand_y=True,
        reroute_stdout=True  # 自动捕获 print 输出
    )],
    [sg.Button("其他操作", key="-OTHER-"), sg.Exit("退出", size=(10, 2))]
]


# ===== 任务函数 =====
def task1_loop():
    global task1_running
    while task1_running:  # 通过标志控制循环
        print(f"[{time.strftime('%H:%M:%S')}] 你好！")
        time.sleep(3)


# ===== 窗口初始化 =====
window = sg.Window(
    "异步任务控制",
    layout,
    resizable=True,
    finalize=True,
    size=(600, 400))
window["-LOG-"].expand(True, True)

# ===== 事件循环 =====
while True:
    event, values = window.read(timeout=100)

    # 退出程序
    if event in (sg.WIN_CLOSED, "退出"):
        if task1_running:
            sg.popup("请先停止任务1！")
        else:
            break

    # 启动任务1
    elif event == "-START-":
        if not task1_running:
            task1_running = True
            # 创建并启动线程
            task1_thread = threading.Thread(
                target=task1_loop,
                daemon=True
            )
            task1_thread.start()
            # 更新按钮状态
            window["-START-"].update(disabled=True)
            window["-STOP-"].update(disabled=False)
            print(f"[{time.strftime('%H:%M:%S')}] 任务1已启动")

    # 停止任务1
    elif event == "-STOP-":
        if task1_running:
            task1_running = False
            if task1_thread is not None:
                task1_thread.join()  # 等待线程结束
            # 更新按钮状态
            window["-START-"].update(disabled=False)
            window["-STOP-"].update(disabled=True)
            print(f"[{time.strftime('%H:%M:%S')}] 任务1已停止")

    # 其他操作示例
    elif event == "-OTHER-":
        if task1_running:
            sg.popup("请先停止任务1！")
        else:
            print("执行其他操作...")

window.close()

if __name__ == "__main__":
    print('x')